package com.heatup.apt.api.service.impl;

import com.heatup.apt.common.constants.UserProductServiceConstants;
import com.heatup.apt.common.dao.ProductServiceDetailMapper;
import com.heatup.apt.common.dao.ProductServiceMapper;
import com.heatup.apt.common.dao.user.UserProductServiceMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.product.ProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heatup.apt.model.user.UserProductService;
import com.heatup.apt.api.service.DataDictService;
import com.heatup.apt.api.service.UserProductServiceService;
import com.baomidou.framework.service.impl.SuperServiceImpl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserProductService 表数据服务层接口实现类
 */
@Service
public class UserProductServiceServiceImpl extends SuperServiceImpl<UserProductServiceMapper, UserProductService> implements UserProductServiceService {
	
	private final static  Logger logger = LoggerFactory.getLogger(UserProductServiceServiceImpl.class);
	
    @Autowired
    private ProductServiceMapper productServiceMapper;

    @Autowired
    private UserProductServiceMapper userProductServiceMapper;
    
    @Autowired DataDictService dataDictService;

    @Autowired
    private ProductServiceDetailMapper productServiceDetailMapper;
    
    public Map<String,Object> addUserMonthTeamCourseProductDays(Integer userId, int dayNum, Integer storeId) {

        Map<String,Object> resultMap = new HashMap<String,Object>();
        ProductService productService = null;
        UserProductService userProductService = null;
        UserProductService oldProductService = null;
        Date vipStartDate = null;
        Date vipEndDate = null;
        //查找该门店对应的团课包月服务
        productService = productServiceMapper.queryMonthlyTeamCourseProductServiceByStoreId(storeId);
        if (productService != null && dayNum > 0) {
            userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(userId, productService.getPServiceType());
            oldProductService = userProductService;
            if (userProductService != null) {
                //如果存在该类型的优惠券，则需要在此基础上直接增加时间段。
                //如果记录是有效的，则在endDate加上天数
                if (userProductService.getIsvalid() == 1) {
                    vipStartDate = DateUtils.getDateShort(userProductService.getEndDate());
                    vipEndDate = DateUtils.AddDays(userProductService.getEndDate(), dayNum);
                    userProductService.setEndDate(vipEndDate);
                    userProductService.setUpdatedBy(userId);
                    userProductService.setUpdatedTime(new Date());
                    userProductService.setIsvaild(1);
                } else {
                    vipStartDate = DateUtils.getDateShort(new Date());
                    vipEndDate = DateUtils.AddDays(new Date(), dayNum);
                    userProductService.setBeginDate(vipStartDate);
                    userProductService.setEndDate(vipEndDate);
                    userProductService.setUpdatedBy(userId);
                    userProductService.setUpdatedTime(new Date());
                    userProductService.setIsvaild(1);
                }
                userProductServiceMapper.updateById(userProductService);
            } else {
                //从未购买过该产品，则需要增加该产品的记录
                userProductService = new UserProductService();
                userProductService.setProductServiceType(productService.getPServiceType());
                userProductService.setUserId(userId);
                vipStartDate = DateUtils.getDateShort(new Date());
                vipEndDate = DateUtils.AddDays(vipStartDate, dayNum);
                userProductService.setIsvaild(1);
                userProductService.setBeginDate(vipStartDate);
                userProductService.setEndDate(vipEndDate);
                userProductService.setCreatedBy(userId);
                userProductService.setCreatedTime(new Date());
                //插入到userProductService
                userProductServiceMapper.insert(userProductService);
            }
        }

        resultMap.put("useBeginDate",vipStartDate);
        resultMap.put("useEndDate",vipEndDate);
        resultMap.put("productService",productService);
        resultMap.put("userProductService",userProductService);

        return resultMap;
    }

    
	@Override
	public UserProductService queryUserProductServiceByUserIdAndType(Integer userId, String type) {
		// 
		return userProductServiceMapper.queryUserProductServiceByUserIdAndType(userId, type);
	}

	
	/**
	 * 获取用户可兑换的年卡天数
	 */
	@Override
	public Integer getUserHasYearCardConvertDateCount(Integer userId) {
		Integer surplusConvertDateCount = 0;
		try {
			
			List<DataDict> minCeductionDayCountList = dataDictService.queryDataDicts("MIN_DEDUCTION_DAY_COUNT");
			Integer minCeductionDayCount = 0;
			Date nowDate = DateUtils.getDateShort(new Date());

			// 获取配置字典表中配置的 至少大于多少会员天数才能兑换餐券的 数值 
			if(minCeductionDayCountList.size() > 0) {
				minCeductionDayCount = Integer.valueOf(minCeductionDayCountList.get(0).getDictCode());
			}
			
			// 用户
			UserProductService userProductService = userProductServiceMapper
					.queryUserProductServiceByUserIdAndType(userId, UserProductServiceConstants.SELFTYPESERVICE);
			
			if(userProductService != null) {
				
				// 如果结束时间小于当前系统时间 并且 是无效状态 剩余天数就是 0 
				if(userProductService.getIsvalid() == UserProductServiceConstants.ISNOTVALID && userProductService.getEndDate().compareTo(nowDate) < 0)
					return 0 ;

				// 获取剩余天数
				Integer surplusDay = 0;
				if(userProductService.getIsvalid() == UserProductServiceConstants.ISVALID) {
					surplusDay = DateUtils.daysBetween(nowDate, DateUtils.getDateShort(userProductService.getEndDate()));
				}else {
					surplusDay = DateUtils.daysBetween(userProductService.getBeginDate(), userProductService.getEndDate());
				}

				// 因为这里的剩余天数是加一天的 这里再减去一天
				surplusDay = surplusDay > 0 ? surplusDay - 1 : surplusDay ;

				if(surplusDay > minCeductionDayCount) {
					surplusConvertDateCount = surplusDay - minCeductionDayCount;
				}
			}
			
			
		} catch (Exception e) {
			// TODO: handle exception
			logger.error("UserProductServiceServiceImpl | getUserHasYearCardConvertDateCount | erro:"+e.toString()+e.getCause(),e);
			
		}
		
		
		return surplusConvertDateCount;
	}

	
	/**
	 * 获取年卡每日单价
	 */
	@Override
	public BigDecimal getYearCardEveyDayPrice() {
		List<DataDict> yearCardEveyDayPriceList = dataDictService.queryDataDicts("YEAR_CARD_EVEY_DAY_PRICE");
		BigDecimal yearCardEveyDayPrice = BigDecimal.ZERO;
		
		// 获取 配置字典表中配置的 每日单价 
		if(yearCardEveyDayPriceList.size() > 0) {
			yearCardEveyDayPrice = new BigDecimal(yearCardEveyDayPriceList.get(0).getDictCode());
		}
		return yearCardEveyDayPrice;
	}


	@Override
	public Integer checkUserHasYearCardService(Integer userId) {
		UserProductService userProductService = userProductServiceMapper.queryUserProductServiceByUserIdAndType(userId, UserProductServiceConstants.SELFTYPESERVICE);
		if(userProductService == null) {
			return 0;
		}
		Integer userHasYearCardService = userProductServiceMapper.checkUserIsHasYearCardService(userId);
		return userHasYearCardService;
	}


	@Override
	public Integer getUserHasYearCardSurplusDateCount(UserProductService userProductService) {
		int surplusDayCount = 0;
		try {
			
			if (userProductService == null) {
				return 0;
			}
			
			if (userProductService.getIsvalid() == 1) {
				surplusDayCount = DateUtils.daysBetween(DateUtils.getDateShort(new Date()), userProductService.getEndDate()) ;
			} else {
				if (userProductService.getBeginDate().compareTo(DateUtils.getDateShort(new Date())) > 0) {
					surplusDayCount = DateUtils.daysBetween(userProductService.getBeginDate(), userProductService.getEndDate()) ;
				}
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return (surplusDayCount > 0 ? surplusDayCount - 1 : surplusDayCount);
	}

}